import 'package:cached_network_image/cached_network_image.dart';
import 'package:find_friend/common/common_widget.dart';
import 'package:find_friend/common/play_audio.dart';
import 'package:find_friend/common/play_audio_flr.dart';
import 'package:find_friend/const/const.dart';
import 'package:find_friend/network/network.dart';
import 'package:find_friend/pages/login&register/model/shared_user_info.dart';
import 'package:find_friend/pages/xspace/detail/xdetailpage.dart';
import 'package:find_friend/pages/xspace/model/school_model.dart';
import 'package:find_friend/pages/xspace/post/xpost_page.dart';
import 'package:flare_flutter/flare_actor.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'mine_photos_wall.dart';

class XpaceTabCommentToolView extends StatelessWidget {

  final int index;
  final ArticleModel model;
  
  final List<String> list = [
    "assets/zhuanfa.png",
    "assets/pinglun.png",
    "assets/zan.png",
    "assets/cai.png",
  ];

  XpaceTabCommentToolView({Key key, this.index, this.model}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    final imageW = (size.width - 81 - 15) / 2.0 / 3;
    return Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              // Image.asset(list[0],width: 13,),
              Icon(const IconData(0xe61a, fontFamily: "iconfont"), size: 20,),
              Container(
                width: imageW,
                alignment: Alignment.center,
                child: Text(model.strReports)
              ),
              Icon(const IconData(0xe601, fontFamily: "iconfont"), size: 20,),
              Container(
                width: imageW,
                alignment: Alignment.center,
                child: Text(model.strReplys)
              ),
              Icon(const IconData(0xe602, fontFamily: "iconfont"), size: 20,),
              Container(
                width: imageW,
                alignment: Alignment.center,
                child: Text(model.strUpvotes)
              ),
              Icon(const IconData(0xe607, fontFamily: "iconfont") ,size: 20,),
            ]
          );
  }
}

class XpaceImageView extends StatelessWidget {
  
  final double imageW;
  final List<Photo> imgUrls;

  const XpaceImageView({
    Key key, 
    @required this.imageW, 
    @required this.imgUrls
  }) : super(key: key);

  Widget _createImageWidget(Photo e){
    return Stack(
            children: [
              PhysicalModel(
                color: Colors.white,
                borderRadius: BorderRadius.circular(5),
                clipBehavior: Clip.antiAlias,
                child: Hero(
                  tag: e.url + imgUrls.indexOf(e).toString(), // 与个人中心区分, hero tag 
                  // child: Image.network(e.url, width: imageW, height: imageW,fit: BoxFit.cover,)
                  child: CachedNetworkImage(
                    imageUrl:e.url, width: imageW, height: imageW,fit: BoxFit.cover,
                  ),
                )
              ),
              Positioned(
                bottom: 5,
                left: 5,
                child: Offstage(
                  offstage: e.ownerUrl == null,
                  child: Image.asset("assets/shengyin3.png")
                ),
              )
            ],
          );
  }

  Widget _imageWidget(int index) {
    if(imgUrls.length > 3 && index == 2) {
      return Stack(
        children: [
          // PhysicalModel(
          //   color: Colors.transparent,
          //   clipBehavior: Clip.antiAlias,
          //   borderRadius: BorderRadius.circular(10),
          //   child: Image.network(imgUrls[index].url, width: imageW,height: imageW,fit: BoxFit.fitWidth),
          // ),
          _createImageWidget(imgUrls[index]),
          Positioned(
            left: 0,
            right: 0,
            bottom: 0,
            top: 0,
            child: Container(
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: Colors.black26,
                borderRadius: BorderRadius.circular(10),
              ),
              child: Text("+${imgUrls.length - 2}", style: instanceTextStyle(15, Colors.white),),
            ),
          )
        ],
      );
    } else {
      return _createImageWidget(imgUrls[index]);
    }
  }

  @override
  Widget build(BuildContext context) {
    
    var count = imgUrls.length;
    if(count > 3) count = 3;
    return Wrap(
              spacing: 5,
              runSpacing: 5,
              children: List.generate(count, (index) => 
                GestureDetector(
                  onTap: (){
                    List<FileModel> temp = imgUrls.map((e) => FileModel(url: e.url, id: 0, audiourl: e.ownerUrl, duration: e.playtime)).toList();
                    Navigator.push(context, PageRouteBuilder(
                      pageBuilder: (BuildContext context, Animation animation,
                          Animation secondaryAnimation) {
                        return new FadeTransition(
                          opacity: animation,
                          child: MinePhotoWallPage(list: temp,heroTag: imgUrls[index].url + index.toString()),
                        );
                      })
                    ); 
                  },
                  child: _imageWidget(index)
                )
              ).toList()
            );  
  }
}

class XspaceVoiceView extends StatefulWidget {
  
  // final String path;
  // final int duration;
  final Voice voice;
  final double width;

  const XspaceVoiceView({Key key, this.width, this.voice}) : super(key: key);

  @override
  _XspaceVoiceViewState createState() => _XspaceVoiceViewState();
}

class _XspaceVoiceViewState extends State<XspaceVoiceView> {
  

  int duration = 0;
  bool isplay = false;
  @override
  void initState() {
    super.initState();
    duration = widget.voice?.playtime ?? 0;
  }

  @override
  void didUpdateWidget(XspaceVoiceView oldWidget) {
    duration = widget.voice?.playtime;
    super.didUpdateWidget(oldWidget);
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: (){
        if(widget.voice == null) return;
        setState(() {
          isplay = !isplay;
        });
        MyNetWorkPlayer.instance.play(sender: widget.voice.url, islocal: widget.voice?.islocal == true, audioduration: widget.voice.playtime, onPlayDuration: (second){
          setState(() {
            duration = (widget.voice.playtime - second) == -1 ? widget.voice.playtime : (widget.voice.playtime - second);
            if((widget.voice.playtime - second) == -1) isplay = false;
            print("${widget.voice.playtime - second}");
          });
        });
      },
      child: Container(
        width: widget.width,
        padding: const EdgeInsets.symmetric(vertical: 3, horizontal: 5),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(20),
          color: APP_main_color,
        ),
        child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              Image.asset(isplay ? "assets/bofang_pause.png" : "assets/bofang22.png", height: 13.5,),
              Container(
                height: 15,
                width: widget.width / 2.0,
                padding: const EdgeInsets.symmetric(vertical: 2),
                child: FlareActor("assets/flr/record.flr", color: Colors.white, alignment:Alignment.center, fit:BoxFit.fitWidth, animation: isplay ? "record" : "stop")
              ),
              Text("$duration‘‘", style: instanceTextStyle(14, Colors.white),)
            ],
          ),
      ),
    );
  }
}

class MineXSpaceView extends StatefulWidget {
  
  final bool showPostButton;
  final String mobile;
  final bool isblack;

  const MineXSpaceView({Key key, this.showPostButton = true, this.mobile, this.isblack = false}) : super(key: key);

  @override
  _MineXSpaceViewState createState() => _MineXSpaceViewState();
}

class _MineXSpaceViewState extends State<MineXSpaceView> {


  RefreshController _refreshController = RefreshController(initialRefresh: true);
  List<ArticleModel> list = [];
  int page = 0;
  Set<int> years = {}; // 年份

  @override
  void initState() {
    super.initState();

  }

  @override
  void dispose(){
    _refreshController.dispose();
    super.dispose();
  }

  _onRefresh() {
    page = 1;
    _request(isrefresh: true);
  }

  _onLoading() {
    page += 1;
    _request();
  }

  _endrefres() {
    if(_refreshController.isRefresh) _refreshController.refreshCompleted();
    if(_refreshController.isLoading) _refreshController.loadComplete();
  }

  _endNormoreData(int perpage) {
    if(perpage < 5) {
      _refreshController.loadNoData();
    } else {
      _refreshController.loadComplete();
    }
  }

  _request({bool isrefresh = false}) {
    var params = {"rows":5, "page":page, "main": widget.isblack, "mobile": widget.mobile};
    Networktool.request(API.article, params: params, method: NETWORKHTTPMethod.GET, success: (data){
      if(data != null) {
        ArticleResponModel model = ArticleResponModel.fromJson(data);
        _endNormoreData(model.data.data?.length ?? 0);

        // 设置分组年份
        model.data?.data?.forEach((element) { 
          int y = DateTime.fromMillisecondsSinceEpoch(element.createtime * 1000).year;
          years.add(y);
        });
        setState(() {
          if(isrefresh) list.clear();
          list.addAll(model.data?.data);
        });
      }
    }
    ,finaly: _endrefres
    );
  }

  String _getMonth(int createTime) {
    return DateTime.fromMillisecondsSinceEpoch(createTime * 1000).month.toString();
  }
  String _getYear(int createTime) {
    return DateTime.fromMillisecondsSinceEpoch(createTime * 1000).year.toString();
  }
  String _getDay(int createTime) {
    return DateTime.fromMillisecondsSinceEpoch(createTime * 1000).day.toString();
  }

  // 计算时间线的长度
  double _computiHeight(ArticleModel m) {
    double height = 20;
    if(m.content != null) height += 30;
    if(m.photo != null) height += 90;
    if(m.voice != null) height += 30;
    return height;
  }

  String _getDateWithModel(ArticleModel m) {
    return _getMonth(m.createtime) + _getDay(m.createtime);
  }

   bool _comshowDate(index) {
    if(index == 0) return false;
    final curr = list[index];
    final lastm = list[index - 1];
    return _getDateWithModel(curr) == _getDateWithModel(lastm);
  }

  Widget _getRequestWidget() {
    final size = MediaQuery.of(context).size;
    final imageW = (size.width - 19.5 - 25 - 20 - 20 - 44 - 15) / 3.0;
    if(list.length == 0) {
      return SizedBox(
        width: size.width,
        child: PreviewNoDataPlaceholder()
      );
    }
    return ListView.builder(
      padding: const EdgeInsets.only(top: 7, left: 20, right: 20, bottom: 20),
      itemCount: list.length,
      itemBuilder: (context, index){
        final m = list[index];
        if(index > 1 && years.length > 1) {
          return Container(
            padding: const EdgeInsets.only(top: 25),
            child: Text("2019年", style: instanceTextStyle(18, Colors.black,fontWeight: FontWeight.bold),),
          );
        }
        return InkWell(
          onTap: (){
            push(context, XDetailPage(model: list[index], onRefreshData: _onRefresh));
          },
          child: Container(
            padding: const EdgeInsets.only(top: 15),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  child: Column(
                    mainAxisSize: MainAxisSize.max,
                    children: [
                      SizedBox(
                        width: 20,
                        child: Offstage(
                          offstage: _comshowDate(index),
                          child: Column(
                            children: [
                              Text(_getDay(m.createtime),style: instanceTextStyle(14, APP_font_black, fontWeight: FontWeight.w500)),
                              Text("${_getMonth(m.createtime)}月",style: instanceTextStyle(11, APP_font_black, fontWeight: FontWeight.w500)),
                              SizedBox(height: 7,),
                            ],
                          ),
                        ),
                      ),
                      Container(
                        height: _comshowDate(index) ? _computiHeight(m) + 50 :  _computiHeight(m),
                        child: VerticalDivider(width: 0.5,color: APP_font_deep_grey),
                      ),
                    ],
                  ),
                ),
                Expanded(
                  child: Container(
                    margin: const EdgeInsets.only(top: 8, left: 19.5),
                    // semanticContainer: true,
                    // clipBehavior: Clip.antiAlias,
                    // shape: RoundedRectangleBorder(
                    //   borderRadius: BorderRadius.circular(8.0),
                    // ),
                    
                    // elevation: 3,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(10),
                      boxShadow: [
                        BoxShadow(blurRadius: 10, spreadRadius: 1, offset: Offset(1, 1), color: Colors.black26)
                      ]
                    ),
                    child: Padding(
                      padding: const EdgeInsets.fromLTRB(19.5, 20, 25, 0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Offstage(
                            offstage: m.content == null,
                            child: Padding(
                              padding: const EdgeInsets.only(bottom: 10),
                              child: Text(m.content ?? "", style: instanceTextStyle(12, APP_font_black), maxLines: 2),
                            ),
                          ),
                          Offstage(
                            offstage: m.photo == null,
                            child: Padding(
                              padding: const EdgeInsets.only(left:6, bottom: 10),
                              child: XpaceImageView(
                                imageW: imageW, 
                                imgUrls: m.photo ?? []
                              )
                            ),
                          ),
                          Offstage(
                            offstage: m.voice == null,
                            child: XspaceVoiceView(width: imageW * 2, voice: m.voice,),
                          ),
                          Padding(
                            padding: EdgeInsets.symmetric(vertical: 10),
                            child: XpaceTabCommentToolView(index: index, model: m,),
                          )
                        ],
                      ),
                    ),
                  ),
                )
              ],
            ),
          ),
        );
    });
  }

  @override
  Widget build(BuildContext context) {
    
    final padding = MediaQuery.of(context).padding;

    return Stack(
      children: [
        CustomRefreshWidget(
            onRefresh: _onRefresh,
            onLoading: _onLoading,
            controller: _refreshController,
            page: page,
          child: _getRequestWidget()
        ),
        Positioned(
          right: 8,
          bottom: 30 + padding.bottom / 2,
          child: Offstage(
            offstage: !widget.showPostButton,
            child: InkWell(
              onTap: (){
                push(context, XPostPage());
              },
              child: Image.asset("assets/bianji1.png"),
            ),
          ),
        )

      ],
    );
  }
}

